package cn.java75.sp.web;

import cn.java75.sp.entity.LoginUser;
import cn.java75.sp.service.AdminService;
import cn.java75.sp.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AdminService adminService;


    @PostMapping("/login")
    public AjaxResult login(LoginBody u){
        System.out.println("???????????????!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        LoginUser login = adminService.login(u.getUsername(), u.getPassword());
        ServletRequestAttributes  attributes = (ServletRequestAttributes)(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        String uuid= UUID.randomUUID().toString();

        response.setHeader("token",uuid);
        request.setAttribute("token",uuid);
        this.redisTemplate.opsForValue().set(uuid,login);

        return AjaxResult.success("ok",uuid);
    }
    @RequestMapping("/success")
    public AjaxResult success(){
        ServletRequestAttributes  attributes = (ServletRequestAttributes)(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = attributes.getRequest();
        //HttpServletResponse response = attributes.getResponse();
        String token=(String)request.getAttribute("token");
        //String token2=request.getHeader("token");
        System.out.println("%%%%%%%%%%%%%%%?????????????????@##@"+token);
        return AjaxResult.success("ok1234567",token);
    }
    @RequestMapping("/")
    public AjaxResult success2(){
        return AjaxResult.success("success ok2222222");
    }
}
